package cn.schoolwow.quickdao.test.module.business.user.dql.general.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.test.entity.Department;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import org.junit.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InitialDepartmentFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DAO dao = flowContext.checkInstanceData(DAO.class);

        dao.rebuild(Department.class);
        insertDepartment1(flowContext);
        insertDepartment2(flowContext);
    }

    @Override
    public String name() {
        return "初始化部门表";
    }

    private void insertDepartment1(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        Map<Long,Integer> parentIdDepartmentCountMap = (Map<Long, Integer>) flowContext.getData("parentIdDepartmentCountMap", new HashMap<>());

        dao.startTransaction(transaction -> {
            Department parentDepartment = new Department();
            {
                parentDepartment.setName("部门1");
                int effect = transaction.insert(parentDepartment);
                Assert.assertEquals(1, effect);
            }
            List<Department> childrenDepartmentList = new ArrayList<>();
            {
                Department childDepartment = new Department();
                childDepartment.setName("部门1的子部门1");
                childDepartment.setParentId(parentDepartment.getId());
                childrenDepartmentList.add(childDepartment);
            }
            {
                Department childDepartment = new Department();
                childDepartment.setName("部门1的子部门2");
                childDepartment.setParentId(parentDepartment.getId());
                childrenDepartmentList.add(childDepartment);
            }
            int effect = transaction.insert(childrenDepartmentList);
            Assert.assertEquals(childrenDepartmentList.size(), effect);

            parentIdDepartmentCountMap.put(parentDepartment.getId(), childrenDepartmentList.size());
        });
    }

    private void insertDepartment2(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        Map<Long,Integer> parentIdDepartmentCountMap = (Map<Long, Integer>) flowContext.getData("parentIdDepartmentCountMap", new HashMap<>());

        Department department = new Department();
        department.setName("部门2");
        int effect = dao.insert(department);
        Assert.assertEquals(1, effect);

        parentIdDepartmentCountMap.put(department.getId(), 1);
    }
}
